<%@page import="com.dhtmlx.planner.controls.DHXLightboxSelectOption"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@ page import="org.hibernate.SessionFactory"%>
<%@ page import="org.hibernate.Session"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Calendar" %>
<%@ page import="hibernate.model.*"%>
<%@ page import="hibernate.util.HibernateUtil"%>
<%@ page import="hibernate.method.*"%>
<html>
<% if(request.getParameter("local_id") == null){
	out.println("<script>alert(\"Nie wybrales lokalu\")</script>");
	response.sendRedirect("../social/index.jsp?page=events&group=newReservation");
	}


Integer user_id = (Integer) session.getAttribute("user_id");
	SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
Session ses= sessionFactory.openSession();
UserMethods um = new UserMethods();
LocalMethods lm = new LocalMethods();
Local loc = lm.findLocalById(sessionFactory, ses, Integer.parseInt(request.getParameter("local_id")));
	%>
	
<h3 style="text-align: center">
<b>System rezerwacji stolików i gier w lokalach HexGames</b>
<br>

Lokal: <%out.println(loc.getCountry()+", " + loc.getCity()+", " + loc.getStreet() + " " + loc.getLocal_number()); %> </h3>
<h5> Zalogowany jako: 
<%if(user_id == null){
	out.print("Uzytkownik anonimowy");
}
else out.println(um.id_to_user(sessionFactory, ses, user_id).getUsername());
	
	%>


</h5>
<!-- <script src="codebase/locale/locale_pl.js" charset="utf-8"></script>-->
<link rel="stylesheet" href="css/reservationSchedulerstyle.css">
<body>
	<div class="planner" id="planner"><%=getPlanner(request)%></div>
	<%@ page import="com.dhtmlx.planner.*,com.dhtmlx.planner.data.*"%>
	<%@ page import="com.dhtmlx.planner.DHXPlanner"%>
	<%@ page import="com.dhtmlx.planner.DHXSkin"%>
	<%@ page import="com.dhtmlx.planner.controls.DHXLightboxSelect" %>
	<%@ page import="com.dhtmlx.planner.controls.DHXLightboxText"%>
	<%@ page import="com.dhtmlx.planner.controls.DHXLightboxTime" %>
	<%@ page import="com.dhtmlx.planner.controls.DHXTimelineView"%>
	<%@ page import="com.dhtmlx.planner.controls.DHXTimelineView.RenderModes"%>;
	<%@ page import="com.dhtmlx.planner.controls.DHXTimelineView.XScaleUnits"%>
	<%@ page import="com.dhtmlx.planner.data.DHXDataFormat"%>
	<%@ page import="com.dhtmlx.planner.extensions.DHXExtension" %>
	
	<%!String getPlanner(HttpServletRequest request) throws Exception {
		DHXPlanner s = new DHXPlanner("./codebase/", DHXSkin.TERRACE);
		s.setWidth(1000);
		s.config.setDblClickCreate(true);
		s.config.setClickFormDetails(false);
		s.setHeight(126);
		s.setInitialDate(2013, 3, 8);
		s.setInitialView("timeline");
		DHXTimelineView view = new DHXTimelineView("timeline", "table",
				"Booking");
		view.setRenderMode(RenderModes.TREE);
		view.setXScaleUnit(XScaleUnits.MINUTE);
		view.setXStep(60);
		view.setXSize(12);
		view.setSectionAutoheight(false);
		view.setXStart(10);
		view.setXLength(24);
		view.setDx(110);
		view.setDy(46);
		view.setFolderDy(20);
		view.setEventDy(41);
		view.setServerList("tables_tree");
		view.setTabClass("dhx_cal_tab_standalone");
		s.views.clear();
		s.views.add(view);
		view.setTabPosition(10);

		// clear default lightbox fields
		s.lightbox.clear();
		// contact details field
		DHXLightboxText contacts = new DHXLightboxText("contacts",
				"Dane kontaktowe");
		contacts.setHeight(40);
		contacts.setFocus(true);
		s.lightbox.add(contacts);
		
		DHXLightboxText user = new DHXLightboxText("user",
				"Numer identyfikacyjny uzytkownika");
		user.setHeight(20);
		user.setFocus(true);
		s.lightbox.add(user);
		
		
		DHXLightboxSelect local = new DHXLightboxSelect("local", "Lokal");
		local.setServerList("locals");
		s.lightbox.add(local);
		
		DHXLightboxSelect game = new DHXLightboxSelect("game", "Gra");
		SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
		Session ses= sessionFactory.openSession();
		AssortmentMethods am = new AssortmentMethods();
		GameMethods gm = new GameMethods();
		game.addOption(new DHXLightboxSelectOption("null", "Nie rezerwuje gry"));
		if(am.listAvailableGamesInLocal(sessionFactory, ses, Integer.parseInt(request.getParameter("local_id"))) != null){
		List <Game> gamesL = am.listAvailableGamesInLocal(sessionFactory, ses, Integer.parseInt(request.getParameter("local_id")));
		for (Game g : gamesL){
			System.out.println(g.getGame_id());
			DHXLightboxSelectOption d = new DHXLightboxSelectOption(g.getGame_id(), g.getName());
		game.addOption(d);
		}
		}
		s.lightbox.add(game);
		
		
		DHXLightboxText notes = new DHXLightboxText("notes", "Informacje dodatkowe");
		notes.setHeight(40);
		s.lightbox.add(notes);
		// table field
		DHXLightboxSelect table = new DHXLightboxSelect("table", "Stolik");
		table.setServerList("tables");
		s.lightbox.add(table);
		// time field
		DHXLightboxTime time = new DHXLightboxTime("time", "Przedzial czasu");
		s.lightbox.add(time);

		// configuring templates
		s.templates.setTimelineDate("{date1:date(%j %F %Y)}");

		// configuring sizes and times
		s.xy.setBarHeight(76);
		s.config.setFixTabPosition(false);
		s.config.setTimeStep(60);
		s.config.setFirstHour(10);
		s.config.setLastHour(24);
		s.config.setLimitTimeSelect(true);

		s.calendars.attachMiniCalendar();
		s.extensions.add(DHXExtension.COLLISION);
		s.extensions.add(DHXExtension.CONTAINER_AUTORESIZE);
		s.setInitialDate(Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
		s.load("events/events.jsp?local_id="+ request.getParameter("local_id"), DHXDataFormat.JSON);
		s.data.dataprocessor.setURL("events/events.jsp?local_id="+ request.getParameter("local_id"));
		return s.render();
	}%>
	
<script src="./codebase/ext/dhtmlxscheduler_readonly.js"></script>
	<script>
	//scheduler.config.readonly = true;
	
	<% //Integer user_id = (Integer) session.getAttribute("user_id");
                 //	SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
            	//	Session ses= sessionFactory.openSession();
                 
                 	EventMethods evm = new EventMethods();
                 	
                	if (user_id !=null){
                 		if ("client".equals(um.getUserType(sessionFactory, ses, user_id))){
                 			List<Reservation> ev = evm.listByUser(sessionFactory, ses, user_id);
                 			if(ev != null){
                 				for (Reservation r: ev){
                 					System.out.println(r.getEvent_id());
                 					%>
                 					//scheduler.attachEvent("onDblClick", function(id, e) {
                 					//if (scheduler.getEvent(id).section_id != ) {
                 						//return false;
                 					//}
                 					//return true;
                 					//});
                 				<%}
                 			}
                 			}
                 			}%>
	
             	scheduler.templates.timeline_scale_label = function(section_id, section_label, section_options){
                     	if (section_options.level > 0)
                              	return "<div class='table " + (section_options.smoking ? "smoking" : "no-smoking") + "'></div><div class='tablename'>" + section_options.name + "</div>";
                     	else
                              	return section_options.name;
             	};
             	scheduler.templates.event_bar_text = function(start, end, ev) {
                     	return "<strong>Rezerwacja</strong><br>" + (ev.contacts || "") + "";
             	};
 
             	// adding empty contacts to show them in event template
             	scheduler.attachEvent("onEventCreated", function(id){
                     	var ev = scheduler.getEvent(id);
                     	ev.contacts = "";
                     	return true;
             	});
             	
             	// message about reserved tables
             	scheduler.attachEvent("onEventCollision", function() {
             		dhtmlx.message("Podany przedzial czasu dla podanego stolika jest juz zarezerwowany..<br>Prosze wybrac inny przedzial czasu lub stolik.", "error")
             		return true;
             	});


             	scheduler.attachEvent("onLightbox", function(){
                 	var sec = scheduler.formSection("contacts");
                 	<% //Integer user_id = (Integer) session.getAttribute("user_id");
                 	//SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
            		//Session ses= sessionFactory.openSession();
                 //	UserMethods um = new UserMethods();
                 	if (user_id !=null){
                 		if ("client".equals(um.getUserType(sessionFactory, ses, user_id))){
                 			User u = um.id_to_user(sessionFactory, ses, user_id);
                 		%>
                 	sec.setValue(<%
                 			out.print("\"");
                 			if(u.getName() != null)
                 			out.print(String.valueOf(u.getName())+" ");
                 			if(u.getSurname() != null)
                 			out.print(String.valueOf(u.getSurname())+" ");
                 			if(u.getEmail() !=null)
                 			out.print(u.getEmail()+" ");
                 			if(u.getPhone() != null)
                 			out.print(String.valueOf(u.getPhone())+" ");
                 			out.print("\"");
%>);
                 		<%}
                 	}%>
                 	
             	   var section = scheduler.formSection("local");
             		section.setValue(<%=request.getParameter("local_id")%>);
             	   section.control.disabled = true;
             	});

             	scheduler.attachEvent("onLightbox", function(){
             		var user= scheduler.formSection("user");
                 	<%if (user_id == null){ %>
                 		user.setValue(<%out.print("\""+String.valueOf("")+"\"");%>);
                 		user.control.disabled = true;
                     <%	} else { %>
                 	user.setValue(<%out.print("\""+ user_id +"\"");%>);
                 	user.control.disabled = true;
                 	<%} %>
                 	
             	});
             	
             	            	
             	scheduler.form_blocks["time"]={
                     	render:function(sns) {
                              	var time = "";
                              	time += "<select>";
                              	for (var i = 10; i < 24; i++) {
                                      	var hour = i + ":00";
                                      	time+="<option value='"+i+"'>"+hour+"</option>";
                              	}
                              	time += "</select>";
 
                              	return "<div class='dhx_cal_ltext'>"+time+"<strong> &nbsp;&dash;&nbsp; </strong>"+time+"<input type='hidden' value='' /></div>";
                     	},
                     	set_value:function(node,value,ev,config){
                              	var selects = node.getElementsByTagName("select");
                              	var select_start = selects[0];
                              	var select_end = selects[1];
 
                              	var start = ev.start_date.getHours();
                              	for (var i = 0; i < select_start.options.length; i++) {
                                      	if (start == select_start.options[i].value) {
                                               	select_start.selectedIndex = i;
                                               	break;
                                      	}
                              	}
 
                              	var end = ev.end_date.getHours();
                              	for (var i = 0; i < select_end.options.length; i++) {
                                      	if (end == select_end.options[i].value) {
                                               	select_end.selectedIndex = i;
                                               	break;
                                      	}
                              	}
 
                              	var date = node.getElementsByTagName("input")[0];
                              	date.value = scheduler.date.day_start(ev.start_date).getTime();
                     	},
                     	get_value:function(node, ev, config) {
                              	var selects = node.getElementsByTagName("select");
                              	var date = node.getElementsByTagName("input")[0];
 
                              	ev.start_date = new Date();
                              	ev.start_date.setTime(date.value);
                     	    	ev.start_date.setHours(selects[0].options[selects[0].selectedIndex].value);
                              	
                              	ev.end_date = new Date();
                              	ev.end_date.setTime(date.value);
                              	ev.end_date.setHours(selects[1].options[selects[1].selectedIndex].value);
 
                              	if (ev.end_date<=ev.start_date)
                              	    	ev.end_date=scheduler.date.add(ev.start_date,scheduler.config.time_step,"minute");
 
                              	return {
                                      	start_date: ev.start_date,
                                      	end_date: ev.end_date
                              	};
                     	},
                     	focus:function(node){
                              	scheduler._focus(node.getElementsByTagName("select")[0]);
                     	}
             	}

             	
    	</script>
    	
</body>
</html>